<?php
namespace app\common\service;

use app\common\model\AgentAdmin;
use app\common\model\AgentShop;
use app\common\model\User;
use think\Db;

class AgentAdminService {
	
	public function join($agentUid, $userId)
	{
		$agentUser = User::get($agentUid);
		if($agentUser['level'] == \app\admin\model\User::LEVEL_HEADQUARTERS) {
			$agentId = 0;
		} else {
			$agent = AgentShop::get(['user_id' => $agentUid]);
			if (!$agent) {
				return '分享人不是代理';
			}
			
			if ($agent['status'] != AgentShop::STATUS_Y) {
				return '分享人代理身份已禁用';
			}
			$agentId = $agent['id'];
		}
		
		
		$model = new AgentAdmin();
		$row = Db::name('agentAdmin')
			->where(['user_id' => $userId, 'status' => $model::STATUS_NORMAL])
			->find();
		
		if($row) {
			return '您已经是管理员了';
		}
		
		$waitRow  = Db::name('agentAdmin')
			->where(['user_id' => $userId, 'status' => $model::STATUS_WAIT])
			->find();
		if ($waitRow) {
			$res = $model->changetStatus($row['id'], $agentId, $model::STATUS_WAIT);
		} else {
			$res = $model->add($userId, $agentId);
		}
		
		if($res !== false) {
			return true;
		} else {
			return $model->getError();
		}
	}
}
